package com.dg.gaming.server;

import com.dg.gaming.server.data.mysql.*;
import com.dg.gaming.api.common.*;
import nanoxml.XMLElement;
import java.lang.reflect.*;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2009</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 1.0
 */
public class GameData {
    private MemoryClassLoader classLoader = null;
    private Class<GameModel> modelClass = null;
    private Class<ServerTableController> controllerClass = null;
    private DBGame game = null;
    public GameData(DBGame game) throws Exception {
        this.game = game;
        classLoader = new MemoryClassLoader(this.getClass().
                                            getClassLoader(), game.getData());
        try {
            modelClass = (Class<GameModel>) Class.forName(game.
                    getModelclassname());
        } catch (ClassNotFoundException ex) {
            modelClass = classLoader.findClass(game.getModelclassname());
        }
        try {
            controllerClass = (Class<ServerTableController>) Class.forName(game.
                    getMain_class_name());
        } catch (ClassNotFoundException ex1) {
            controllerClass = classLoader.findClass(game.getMain_class_name());
        }

    }

    public DBGame getGame() {
        return game;
    }

    public GameModel getGameModel(XMLElement data) throws Exception {
        if (modelClass == null) {
            return null;
        }
        GameModel model = (GameModel) modelClass.newInstance();
        if (data != null) {
            Method m = modelClass.getMethod("setState", XMLElement.class);
            m.invoke(model, data);

        }
        return model;
    }

    public ServerTableController getController(TableController contr) throws
            Exception {
        if (controllerClass == null) {
            return null;
        }
        Class[] classParams = new Class[] {TableController.class};
        Object[] params = new Object[] {contr};
        Constructor constructor = controllerClass.getConstructor(classParams);
        return (ServerTableController) constructor.newInstance(params);

    }
}
